# API Router Startup Script (PowerShell)
# Set console encoding to UTF-8
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8

Write-Host "========================================" -ForegroundColor Cyan
Write-Host "    API Router Startup Script" -ForegroundColor Yellow
Write-Host "========================================" -ForegroundColor Cyan
Write-Host ""
Write-Host "Starting API Router Server..." -ForegroundColor Green
Write-Host "Server URL: " -NoNewline -ForegroundColor White
Write-Host "http://localhost:3001" -ForegroundColor Blue
Write-Host ""
Write-Host "Press Ctrl+C to stop server" -ForegroundColor Yellow
Write-Host "========================================" -ForegroundColor Cyan
Write-Host ""

# Check if Node.js is installed
try {
    $nodeVersion = node --version 2>$null
    if ($LASTEXITCODE -ne 0) {
        throw "Node.js not found"
    }
    Write-Host "Node.js version: $nodeVersion" -ForegroundColor Green
} catch {
    Write-Host "Error: Node.js not found" -ForegroundColor Red
    Write-Host "Please install Node.js: https://nodejs.org/" -ForegroundColor Yellow
    Read-Host "Press Enter to exit"
    exit 1
}

# Check if dependencies are installed
if (-not (Test-Path "node_modules")) {
    Write-Host "Installing dependencies..." -ForegroundColor Yellow
    npm install
    if ($LASTEXITCODE -ne 0) {
        Write-Host "Dependency installation failed" -ForegroundColor Red
        Read-Host "Press Enter to exit"
        exit 1
    }
    Write-Host "Dependencies installed successfully" -ForegroundColor Green
    Write-Host ""
}

# Check database file
if (-not (Test-Path "db.json")) {
    Write-Host "Warning: db.json file not found" -ForegroundColor Yellow
    Write-Host "Will create default database file..." -ForegroundColor Yellow
}

# Start server
Write-Host "Starting API Router Server..." -ForegroundColor Green
Write-Host ""

# Start the server
node src/main/server.js

# Check exit status
if ($LASTEXITCODE -ne 0) {
    Write-Host ""
    Write-Host "Server startup failed" -ForegroundColor Red
}

# If server exits unexpectedly
Write-Host ""
Write-Host "Server stopped" -ForegroundColor Yellow
Read-Host "Press Enter to exit"